package com.itheima.web.controller.store;

import com.github.pagehelper.PageInfo;
import com.itheima.core.BaseServlet;
import com.itheima.core.ResponseBody;
import com.itheima.domain.store.Catalog;
import com.itheima.domain.store.Company;
import com.itheima.domain.store.Question;
import com.itheima.domain.store.QuestionItem;
import com.itheima.service.store.CatalogService;
import com.itheima.service.store.CompanyService;
import com.itheima.service.store.QuestionService;
import com.itheima.service.store.impl.CatalogServiceImpl;
import com.itheima.service.store.impl.CompanyServiceImpl;
import com.itheima.service.store.impl.QuestionServiceImpl;
import com.itheima.utils.BeanUtil;
import com.itheima.utils.UUIDUtil;
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import org.apache.commons.lang3.StringUtils;

import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.lang.reflect.Parameter;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Map;

@WebServlet("/store/question/*")
public class QuestionServlet extends BaseServlet {
    private QuestionService questionService = new QuestionServiceImpl();
    private CompanyService companyService = new CompanyServiceImpl();//企业
    private CatalogService catalogService = new CatalogServiceImpl();//目录，阶段，类别


    /**
     * 显示列表信息
     */
    public String list(HttpServletRequest request, HttpServletResponse response)throws Exception{
        String pageNum = request.getParameter("pageNum");
        String pageSize = request.getParameter("pageSize");

        if(StringUtils.isBlank(pageNum)){
            pageNum = "1";
        }
        if(StringUtils.isBlank(pageSize)){
            pageSize = "10";
        }

        PageInfo page = questionService.queryPage(Integer.parseInt(pageNum), Integer.parseInt(pageSize));
        request.setAttribute("page",page);
        return "/WEB-INF/pages/store/question/list.jsp";
    }

    /**
     * 根据ID回显数据
     */
    public String toEdit(HttpServletRequest request, HttpServletResponse response)throws Exception{
        String id = request.getParameter("id");

        /*查询当前问题信息*/
        Question question = questionService.findById(id);
        request.setAttribute("question",question);

        List<Company> companies = companyService.findAll();
        List<Catalog> catalogs = catalogService.findAll();
        request.setAttribute("catalogList",catalogs);
        request.setAttribute("companyList",companies);

        return "/WEB-INF/pages/store/question/update.jsp";
    }

    /**
     * 更新数据，更新完毕后跳转到列表页面
     */
    public String edit(HttpServletRequest request, HttpServletResponse response)throws Exception{
        /*1.解析表单数据*/
        List<FileItem> fileItems = new ServletFileUpload(new DiskFileItemFactory()).parseRequest(request);

        /*2.将表单数据封装到实体类中，文件上传的那个框的值（文件名）无法封装到实体类中*/
        Question questionInForm = BeanUtil.fillBean(fileItems, Question.class);

        /*3.遍历表单数据，将文件找到，保存到服务器*/
        for (FileItem fileItem : fileItems) {

            if (fileItem.isFormField()==false&&fileItem.getSize()!=0){
                questionInForm.setPicture(UUIDUtil.getSimpleUUID());
                File file=new File(super.getServletContext().getRealPath("upload"),questionInForm.getPicture());
                fileItem.write(file);
                break;
            }
        }
        questionService.save(questionInForm);

        return "/store/question/list";
    }

    /**
     * 跳转到新建add.jsp页面
     */
    public String toAdd(HttpServletRequest request, HttpServletResponse response)throws Exception{
        List<Company> companies = companyService.findAll();
        List<Catalog> catalogs = catalogService.findAll();
        request.setAttribute("catalogList",catalogs);
        request.setAttribute("companyList",companies);

        return "/WEB-INF/pages/store/question/add.jsp";
    }

    /**
     * 保存，保存完毕后跳转到列表页面
     */
    public String save(HttpServletRequest request, HttpServletResponse response)throws Exception{
        /*1.解析表单数据*/
        List<FileItem> fileItems = new ServletFileUpload(new DiskFileItemFactory()).parseRequest(request);

        /*2.将表单数据封装到实体类中，文件上传的那个框的值（文件名）无法封装到实体类中*/
        Question questionInForm = BeanUtil.fillBean(fileItems, Question.class);

        /*3.遍历表单数据，将文件找到，保存到服务器中*/
        for (FileItem fileItem : fileItems) {
            if (fileItem.isFormField()==false&&fileItem.getSize()!=0){
                questionInForm.setPicture(UUIDUtil.getSimpleUUID());
                File file=new File(super.getServletContext().getRealPath("upload"),questionInForm.getPicture());
                fileItem.write(file);
                break;
            }
        }
        /*4.调用service保存数据*/
        questionService.save(questionInForm);
        return "/store/question/list";
    }

    /**
     * 删除，删除完毕跳转到列表页面
     */
    public String delete(HttpServletRequest request, HttpServletResponse response)throws Exception{
        String[] ids = request.getParameterValues("id");
        questionService.deleteById(ids);
        return "/store/question/list";
    }

    private void downloadReport(HttpServletRequest request, HttpServletResponse response) throws Exception {
        /*1.告诉浏览器返回的是EXCEL文件，并且要下载该文件，不能直接在浏览器打开*/
        response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet;charset=utf-8");
        response.addHeader("Content-Disposition","attachment;fileName="+UUIDUtil.getSimpleUUID()+".xlsx");

        /*2.创建xlns文件，并且将EXCEL中的数据写到内存*/
        ByteArrayOutputStream os = questionService.report();

        /*3.将内存中的数据变成字节数据写入到浏览器中*/
        os.writeTo(response.getOutputStream());

        os.close();
    }

    public Object toExam(HttpServletRequest request, HttpServletResponse response)throws Exception{
        return "/store/question/textPaper";
    }

    @ResponseBody
    public Object textPaper(HttpServletRequest request, HttpServletResponse response)throws Exception{
        List<Question> questions = questionService.textPaper();
        request.setAttribute("questions",questions);
        return "/WEB-INF/pages/store/question/exam.jsp";
    }

    public Object getScore(HttpServletRequest request, HttpServletResponse response)throws Exception{
        //获取所有参数
        Map<String, String[]> parameterMap = request.getParameterMap();
        ArrayList<String> list = new ArrayList<String>();
        parameterMap.forEach((K,V)->{
            if (StringUtils.isNotBlank(V.toString())){
                for (String s : V) {
                    if (s.equals("0")){
                        list.add("0.0");
                        break;
                    }
                }
            }
        });
        int score=100-(list.size()*25);
        request.setAttribute("score",score);
        return "/WEB-INF/pages/store/question/score.jsp";
    }
}
